package cn.lijigou.shopping.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.zip.GZIPInputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import cn.lijigou.shopping.domain.MResult;


public class HttpUtil {
	//解压缩GET
	public static MResult GET_COMPRESS(String url){
			MResult result = null;
			InputStream  in = null;
			HttpGet httpRequest = null;      
			HttpClient httpclient = new DefaultHttpClient();              
			HttpResponse httpResponse;
			try {
				int apn = APNManage.getApnType();
				if(apn == APNManage.CMWAP_APN){
					HttpHost proxy = new HttpHost("10.0.0.172", 80); 
					httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); 
				}
				httpRequest = new HttpGet(url); 
				httpResponse = httpclient.execute(httpRequest);
				if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)             
				{                  
					InflatingEntity ie= new InflatingEntity(httpResponse.getEntity());
					in  = ie.getContent();
					result = new MResult(readStream(in));
					
				}              
			} catch (Exception e) {
				e.printStackTrace();
			}             
		return result;
	}
	//压缩工具
	private static class InflatingEntity extends HttpEntityWrapper {
	    @Override
		public long getContentLength() {
			return super.getContentLength();
		}

		public InflatingEntity(HttpEntity wrapped) {
	        super(wrapped);
	    }

	    @Override
	    public InputStream getContent() throws IOException {
	        return new GZIPInputStream(wrappedEntity.getContent());
	    }

	}
	//不解压缩GET
	public static MResult GET(String url){
		MResult result = null;
		InputStream  in = null;
		HttpGet httpRequest = null;
		HttpClient httpclient = new DefaultHttpClient();              
		HttpResponse httpResponse;
			try {
				int apn = APNManage.getApnType();
				if(apn == APNManage.CMWAP_APN){
					HttpHost proxy = new HttpHost("10.0.0.172", 80); 
					httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); 
				}
				httpRequest = new HttpGet(url); 
				httpResponse = httpclient.execute(httpRequest);
				if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)             
				{                  
					in = httpResponse.getEntity().getContent();
					result = new MResult(readStream(in));
					
				}              
			} catch (Exception e) {
				e.printStackTrace();
			} 
		return result;
	}
	//不解压缩POST
	public static MResult POST(String url,List<NameValuePair>  data){
		MResult result = null;
		try {   
			HttpPost httpRequest = new HttpPost(url);
			int apn = APNManage.getApnType();
			if(apn == APNManage.CMWAP_APN){
				HttpHost proxy = new HttpHost("10.0.0.172", 80); 
				httpRequest.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); 
			}
            // 设置字符集   
            HttpEntity httpentity = new UrlEncodedFormEntity(data, "UTF-8");   
            // 请求httpRequest   
            httpRequest.setEntity(httpentity);   
            // 取得默认的HttpClient   
            HttpClient httpclient = new DefaultHttpClient();   
            // 取得HttpResponse   
            HttpResponse httpResponse = httpclient.execute(httpRequest);   
            // HttpStatus.SC_OK表示连接成功   
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {   
                // 取得返回的字符串   
                String strResult = EntityUtils.toString(httpResponse.getEntity());   
                result = new MResult(strResult);
            } else {   
            	
            }   
        } catch (Exception e) {
			e.printStackTrace();
		} 
		return result;
	}
	
	/*
	 * 返回请求状态
	 * String url 接口地址
	 */
	public static String GET_RESULT_CODE(String url){
		String result_code = "";
		InputStream  in = null;
		HttpGet httpRequest = null;      
			HttpClient httpclient = new DefaultHttpClient();              
			HttpResponse httpResponse;
			try {
				int apn = APNManage.getApnType();
				if(apn == APNManage.CMWAP_APN){
					HttpHost proxy = new HttpHost("10.0.0.172", 80); 
					httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); 
				}
				httpRequest = new HttpGet(url); 
				httpResponse = httpclient.execute(httpRequest);
				if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)             
				{                  
					in = httpResponse.getEntity().getContent();
					byte[] data = readStream(in);
					result_code = new String(data);
					
				}              
			} catch (Exception e) {
				e.printStackTrace();
			}        
		return result_code;
		
	}
	
	/**
	 * 流转换二进制
	 * @author 董永健
	 * @throws Exception
	 */
	public static byte[] readStream(InputStream inputStream) throws Exception{
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0 ;
		while((len = inputStream.read(buffer)) != -1){
			outputStream.write(buffer, 0, len);
		}
		outputStream.close();
		inputStream.close();
		return outputStream.toByteArray();
	}
	
	public static HttpURLConnection getHttpURLConnection(String url){
		//去掉host部分
		HttpURLConnection conn = null;
		String apn_url="";
		try {
			URL u = new URL(url); 
			String hostName = u.getHost();
			if(APNManage.getApnType()==APNManage.CMWAP_APN){
				apn_url =url.replace(hostName, "10.0.0.172:80");
			}else{
				apn_url = url;
			}
			URL u1 = new URL(apn_url); 
			conn = (HttpURLConnection)u1.openConnection(); 
			if(APNManage.getApnType()==APNManage.CMWAP_APN){
				conn.setRequestProperty("X-Online-Host", hostName);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return conn;
	}
}
